﻿using System.IO;

namespace Raven
{
    public class Wall2D : BaseGameEntity
    {
        protected Vector2 m_vA, m_vB, m_vN;
        protected DisplayObject _displayObject;

        void CalculateNormal()
        {
            Vector2 temp = (m_vB - m_vA).normalized;

            m_vN.x = -temp.y;
            m_vN.y = temp.x;
        }

        public Wall2D() : base(Raven.EntityType.Wall)
        {
            CreateDisplayObject();
        }

        public Wall2D(Vector2 A, Vector2 B) : base(Raven.EntityType.Wall)
        {
            m_vA = A;
            m_vB = B;
            CalculateNormal();
            CreateDisplayObject();
        }

        public Wall2D(Vector2 A, Vector2 B, Vector2 N) : base(Raven.EntityType.Wall)
        {
            m_vA = A;
            m_vB = B;
            m_vN = N;
            CreateDisplayObject();
        }

        public Wall2D(BinaryReader reader) : base(Raven.EntityType.Wall)
        {
            Read(reader);
            CreateDisplayObject();
        }

        public Vector2 From()
        {
            return m_vA;
        }

        public void SetFrom(Vector2 v)
        {
            m_vA = v;
            CalculateNormal();
        }

        public Vector2 To()
        {
            return m_vB;
        }

        public void SetTo(Vector2 v)
        {
            m_vB = v;
            CalculateNormal();
        }

        public Vector2 Normal()
        {
            return m_vN;
        }

        public void SetNormal(Vector2 n)
        {
            m_vN = n;
        }

        public Vector2 Center()
        {
            return (m_vA + m_vB) / Fix.Two;
        }

        public void Read(BinaryReader reader)
        {
            m_vA = new Vector2(new Fix(reader.ReadInt32()), new Fix(reader.ReadInt32()));
            m_vB = new Vector2(new Fix(reader.ReadInt32()), new Fix(reader.ReadInt32()));
            m_vN = new Vector2(new Fix(reader.ReadInt32()), new Fix(reader.ReadInt32()));
        }

        public void CreateDisplayObject()
        {
            _displayObject = DisplayObjectFactory.CreateDisplayObject(this);
            _displayObject.Start();
        }

        public override void Destroy()
        {
            _displayObject.Destroy();
        }
    }
}